<?php

namespace App\Service\Pay\SysType;

use App\Console\Commands\Renew\MerchantRenewOrderCommand;
use App\Enums\OpenShop\InvestmentPromotion\ErrCode;
use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteMissionEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Enums\WorkOrder\OrderEnum;
use App\Events\OpenShop\OpenShopProcessEvent;
use App\Events\OpenShop\SignSiteMissionEvent;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Library\FeiShu\SendFs;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignCostMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignSoftOutfitMappingModel;
use App\Models\System\SystemNotifyCenterModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\Common\SmsService;
use App\Service\OpenShop\Feishu\ShopTagsService;
use App\Service\OpenShop\Import\HistoryOrder\HistoryOrderParam;
use App\Service\OpenShop\Message\SendFsService;
use App\Service\OpenShop\Wap\SignOrderService;
use App\Service\System\SystemNotifyService;
use App\Service\WorkOrder\FunctionOpen\FunctionOpenService;
use Illuminate\Support\Facades\Log;
use Kuafu\GeneralFs\BuildFs;

class PayDesignService extends BasePaySysTypeService
{
    public function valid(): void
    {
        // 订单已作废
        if ($this->signOrderModel->status == SignOrderEnum::ORDER_STATUS_NO) {
            throw new CustomHttpResponseException(
                ErrCode::errCodeTrans(ErrCode::CODE_SIGN_ORDER_STATUS_DEL)
            );
        }

        // 订单状态不对
        if ($this->orderModel->orderStatus != OpenShopSpaceDesignCostMappingModel::ORDER_STATUS_0) {
            throw new CustomHttpResponseException(
                ErrCode::errCodeTrans(ErrCode::CODE_ERR_DECORATE_ORDER_STATUS)
            );
        }

        // 支付状态不对
        if (!in_array($this->orderModel->payStatus, [
            OpenShopSpaceDesignCostMappingModel::ORDER_PAY_STATUS_0,
            OpenShopSpaceDesignCostMappingModel::ORDER_PAY_STATUS_1
        ])) {
            throw new CustomHttpResponseException(
                ErrCode::errCodeTrans(ErrCode::CODE_ERR_DECORATE_PAY_STATUS)
            );
        }
    }

    public function priceLists(): array
    {
        return collect([
            [
                'name'  => '设计费',
                'price' => $this->orderModel->designFee,
            ],
            [
                'name'  => '商户通',
                'price' => $this->orderModel->merchantFee,
            ],
            [
                'name'  => '超标设计费',
                'price' => $this->orderModel->overDesignFee,
            ],
        ])->filter(function ($item) {
            if ($item['price'] == 0) {
                return false;
            }

            return true;
        })->values()->toArray();
    }

    public function paySuccessCheck(): bool
    {
        // 主订单已支付完成、直接返回成功 - 幂等
        if ($this->orderModel->payStatus >= OpenShopSpaceDesignCostMappingModel::ORDER_PAY_STATUS_2) {
            return true;
        }

        return false;
    }

    public function paySuccessSaveOrder(int $amount): void
    {
        $this->orderModel->onePaySuccess($amount);
    }

    // 设计费支付成功要干的事
    public function paySuccessAfter(): void
    {
        if ($this->orderModel->orderStatus != OpenShopSpaceDesignCostMappingModel::ORDER_STATUS_1) {
            return;
        }

        if (HistoryOrderParam::$forceCurrentUser) {
            $uid = HistoryOrderParam::$forceCurrentUser->id;
        } else {
            $uid = $this->signOrderModel->merchantUserId;
        }

        // 单笔部分支付
        if ($this->orderModel->payStatus == OpenShopSpaceDesignCostMappingModel::ORDER_PAY_STATUS_1) {

            // 流程日志
            event(new OpenShopProcessEvent($uid, $this->signOrderModel->mainProcessId,
                MainProcessEnum::MAIN_PROCESS_SPACE_DESIGN, MainProcessEnum::SPACE_DESIGN_STEP_TYPE_DESIGN_MODULE_PAY));
            return;
        }

        $nowStepStatus = OpenShopMainProcessModel::query()
                                                 ->where('orderNo', $this->signOrderModel->orderNo)
                                                 ->value('nowStepStatus');

        if ($nowStepStatus != MissionTemplateEnum::STEP_STATUS_14) {

            // 只有一个单子的时候关闭任务
            OpenShopSiteMissionModel::finishBranchMission($this->signOrderModel->orderNo,
                MissionTemplateEnum::STEP_STATUS_14);

            // 更新设计模块标签
            (new ShopTagsService($this->signOrderModel->orderNo))->updateDesignPayTag();

        } else {

            Log::info('支付设计模块', [
                'orderNo' => $this->signOrderModel->orderNo,
                'status'  => MainProcessEnum::SPACE_DESIGN_STEP_TYPE_DESIGN_CONFIRM_EQUIPMENT_MODULE
            ]);
            // 更新space_design表step
            OpenShopSpaceDesignModel::updateStep($this->signOrderModel->orderNo,
                MainProcessEnum::SPACE_DESIGN_STEP_TYPE_DESIGN_CONFIRM_EQUIPMENT_MODULE);

            // 正常流程 - 支付成功，进行下一个任务
            event(new SignSiteMissionEvent($this->signOrderModel->orderNo, MissionTemplateEnum::STEP_STATUS_14,
                $this->signOrderModel->merchantUserId));

            //装支付完成之后的推送 , 放置代码最后
            try {
                $existsOrderCount = OpenShopSpaceDesignCostMappingModel::query()
                                                                       ->where('orderNo', $this->signOrderModel->orderNo)
                                                                       ->where('payStatus',OpenShopSpaceDesignCostMappingModel::ORDER_PAY_STATUS_2)
                                                                       ->where('orderStatus', '!=',
                                                                           OpenShopSpaceDesignCostMappingModel::ORDER_STATUS_3)
                                                                       ->count();

                if ($existsOrderCount > 1) {
                    MerchantRenewOrderCommand::fsMsgSend($this->signOrderModel);
                }

                // 更新设计模块标签
                (new ShopTagsService($this->signOrderModel->orderNo))->updateDesignPayTag();

                $this->notify();
            } catch (
            \Exception $exception
            ) {
                BuildFs::newRobot(SendFs::ROBOT_WARNING)->setTitleContent('商户通支付通知模块异常', $exception)->send();
            }
        }

        if (!HistoryOrderParam::$importOrderMode) {

            // 群消息推送
            SignOrderService::prepareOrderPaySuccessFsGroup($this->signOrderModel->orderNo, '设计');
        }

        // 流程日志
        event(new OpenShopProcessEvent($uid, $this->signOrderModel->mainProcessId,
            MainProcessEnum::MAIN_PROCESS_SPACE_DESIGN, MainProcessEnum::SPACE_DESIGN_STEP_TYPE_DESIGN_MODULE_PAY));
    }

    /**
     * 消息推送
     *
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Overtrue\EasySms\Exceptions\InvalidArgumentException
     */
    public function notify(): void
    {
//
//        // 飞书通知
//        (new SendFsService($this->signOrderModel->orderNo))->choubeiSend();
//        (new SendFsService($this->signOrderModel->orderNo))->notifyChoubeiShangHuTongSend();
//
//        // 短信通知
//        (new SmsService())->aliyunSend($this->signOrderModel->baseInfoRel->mobile,
//        config('sms.template.workOrderOpenShouYinjiNotify'), []);
//
//        // 门店提送提醒
//        $pushUidMap = array_values(
//        array_column(
//        (RmsUserRemote::getShopManagerUserByShopId([$this->signOrderModel->progressRel->shopId])['lists'] ?? []),
//        "userId"
//        )
//        );
//
//        SystemNotifyService::customerBatchPush(
//        $pushUidMap,
//        '开通夸父收银功能提醒',
//        "尊敬的夸父伙伴您好，夸父提醒您：收银系统需要申请收款账号，请点击查看详情，提交资料，申请功能开通。",
//        config('webUrl.notify_web_cdn_url') . '#/pages/work-order/function-activation/form/index?type=100',
//        $this->signOrderModel->mainProcessRel->shopId,
//        SystemNotifyCenterModel::NOTIFY_TYPE_5
//        );
//

        // 判断商户通
        $merchantFeeTotal = OpenShopSpaceDesignCostMappingModel::query()
                                                               ->where('orderNo', $this->signOrderModel->orderNo)
                                                               ->where('payStatus',
                                                                   OpenShopSpaceDesignCostMappingModel::ORDER_PAY_STATUS_2)
                                                               ->where('orderStatus', '!=',
                                                                   OpenShopSpaceDesignCostMappingModel::ORDER_STATUS_3)
                                                               ->sum('merchantFee');
        $pushUidMap       = array_values(
            array_column(
                (RmsUserRemote::getShopManagerUserByShopId([$this->signOrderModel->progressRel->shopId])['lists'] ?? []),
                "userId"
            )
        );

        Log::info('shanghutong_notify_2_1', [
            'orderNo'          => $this->signOrderModel->orderNo,
            'merchantFeeTotal' => $merchantFeeTotal,
            'pushUidMap'       => $pushUidMap,
        ]);

        if ($merchantFeeTotal > 0) {
            // 飞书通知
            (new SendFsService($this->signOrderModel->orderNo))->notifyChoubeiShangHuTongSend();

            SystemNotifyService::customerBatchPush(
                $pushUidMap,
                '开通夸父点评商户通提醒',
                "尊敬的夸父伙伴您好，您已完成点评商户通费用的支付。请点击查看详情，提交资料，申请点评商户通功能。",
                config('webUrl.notify_web_cdn_url') . '#/pages/work-order/function-activation/form/index?type=103',
                $this->signOrderModel->mainProcessRel->shopId,
                SystemNotifyCenterModel::NOTIFY_TYPE_5
            );
        }
    }
}
